package org.example.controller;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.example.enums.CouponCategoryEnum;
import org.example.interceptor.LoginInterceptor;
import org.example.model.LoginUser;
import org.example.request.NewUserCouponRequest;
import org.example.service.CouponService;
import org.example.util.JsonData;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author LinN
 * @since 2022-09-29
 */
@RestController
@RequestMapping("/api/coupon/v1")
@Api(tags = "优惠券模块")
@Slf4j
public class CouponController {

    @Autowired
    private CouponService couponService;

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 分页查询优惠券
     */
    @ApiOperation("分页查询优惠券")
    @GetMapping("page_coupon")
    public JsonData couponPage(@ApiParam(value = "当前页码", required = true) @RequestParam(defaultValue = "1") int page,
                               @ApiParam(value = "每页显示多少条", required = true) @RequestParam(defaultValue = "5") int size) {
        Map<String, Object> pageMap = couponService.pageCouponActivity(page, size);
        return JsonData.buildSuccess(pageMap);
    }

    @ApiOperation("领取促销优惠券")
    @GetMapping("/add/promotion/{coupon_id}")
    public JsonData addCoupon(@ApiParam(value = "优惠券id", required = true)
                              @PathVariable(value = "coupon_id", required = true) Long couponId) {

        LoginUser user = LoginInterceptor.threadLocal.get();
        String lockKey = "lock:coupon:" + couponId + ":" + user.getId();
        RLock rLock = redissonClient.getLock(lockKey);
        rLock.lock();
        try {
            JsonData jsonData = couponService.addCoupon(couponId, CouponCategoryEnum.PROMOTION);
            return jsonData;
        } finally {
            log.info("解锁成功");
            rLock.unlock();
        }
    }

    /**
     * 新人发放优惠券
     */
    @ApiOperation("新人发放优惠券")
    @PostMapping("new_user_coupon")
    public JsonData addNewUserCoupon(@ApiParam("用户对象") @RequestBody NewUserCouponRequest newUserCouponRequest) {
        JsonData jsonData = couponService.initNewUserCoupon(newUserCouponRequest);
        return jsonData;
    }

}

